/* eslint-disable */
import { wxConfig, loginByWxcode, bindSuperior } from '@/api/login'
import { isWeixinCient } from '@/utils/validate'
import { routeTo } from '@/utils/index'
import Store from '@/utils/store'
import router from '../../router'

const user = {
  state: {
    wxConfig: '',
    sid: '',
    pid: '',
    displayOriginalPrice:'' // displayOriginalPrice:显示原价1，不显示0
  },

  mutations: {
    SET_WXCONFIG: (state, wxConfig) => {
      state.wxConfig = wxConfig
    },
    SET_SID: (state, sid) => {
      state.sid = sid
    },
    SET_PID: (state, pid) => {
      state.pid = pid
    },
    SET_DISPLAYORIGINALPRICE: (state, displayOriginalPrice) => {
      state.displayOriginalPrice = displayOriginalPrice
    }
  },

  actions: {
    /**context
     * 获取wxConfig
     * @params 获取config传的参数
     **/
    getWxConfig(context) {
      return new Promise((resolve, reject) => {
        const param = {}
        // 是否第一次打开浏览器
        const is_not_first = Store.fetch('isNotFirst')
        if (is_not_first != 1) {
          Store.save('isNotFirst', 1)
        }
        param.is_not_first = is_not_first ? 1 : 0
        const query = router.currentRoute.query
        if(!query.code){
          Store.saveLocal('query', query)
        }
        param.uri = window.location.href
        param.pid = query.pid
        param.sid = query.sid
        // param.detailId = query.detailId
        if (param.pid && param.pid != 'underfind' && param.pid != 0) Store.saveLocal('pid', param.pid)
        if (param.sid) Store.saveLocal('sid', param.sid)
        // if (param.detailId && param.detailId != 'null') Store.saveLocal('detailId', param.detailId)
        if (!query.sid) { // 微信返回的链接没带上sid
          param.sid = Store.fetchLocal('sid')
        }
        wxConfig(param).then(res => {
          if (res.status === 1) {
            if(res.data && res.data.logo){
              const link = document.querySelector("link[rel*='icon']")
              link.href = res.data.logo;
            }
            // console.log(res.data, '配置');
            var officialInfo = {};
            officialInfo.is_official_account = res.data.is_official_account || '';
            officialInfo.account_img = res.data.account_img || '';
            officialInfo.account_name = res.data.account_name || '';
            officialInfo.must_official_account = res.data.must_official_account || ''
            Store.saveLocal('officialInfo',officialInfo)


            const appId = res.data.appId
            const scope = res.data.scope
            const jsapi_url=res.data.jsapi_url
            const redirect_uri = encodeURIComponent(res.data.jsapi_url)

            if (res.data.is_login === 0 || res.data.current_uid == 0) { // 未登录
              const wxUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`
              if (isWeixinCient()) {
                // 微信环境中
                const pid = Store.fetchLocal('pid')
                const sid = Store.fetchLocal('sid')
                // const uid = Store.fetchLocal('uid')
                const queryData = query
                if (queryData.code) { // 微信返回的链接
                  const param = { code: queryData.code }
                  loginByWxcode(param).then(resp => {
                    if (resp.status === 1) {
                      const uid = resp.data.uid

                      if (uid) {
                        Store.saveLocal('uid', uid)
                        routeTo(sid, uid)
                      }
                    } else {
                      // Toast(res.msg)
                      location.reload()
                    }
                  })
                } else { // 非微信返回的链接，未登录则跳转到微信登录
                  location.href = wxUrl
                }
              } else {
                // console.log('非微信环境')
                resolve();
              }
            } else { // 已登录
              const uid = res.data.current_uid
              Store.saveLocal('uid', uid)
              if (query.code && query.state) { // 微信返回的链接
                routeTo(param.sid, uid)
              } else { // 非微信返回的链接，未登录则跳转到微信登录
                if (!query.pid) { // 后台复制的链接没有pid
                  history.pushState({},'',jsapi_url);
                  // location.href = jsapi_url
                } else if (uid !== param.pid) {
                  if(param.pid!=0){
                    // pid不是自己的时候绑定上级
                    let params = { pid: param.pid }
                    // 企业微信直播 绑定上下级
                    if (query.ww_share_code) {
                      params.ww_share_code = query.ww_share_code

                    }
                    bindSuperior(params).then(res => {
                      // alert(`${uid}绑定上级${param.pid}`)
                      routeTo(param.sid, uid)
                    })
                  }else{
                    routeTo(param.sid, uid)
                  }
                }
              }
            }
            context.commit('SET_WXCONFIG', res.data)
            context.commit('SET_SID', Store.fetchLocal('sid'))
            context.commit('SET_PID', Store.fetchLocal('pid'))
          }
          resolve(res)
        }).catch(error => {
          vm.$toast(error)
          resolve(error)
        })
      })
    },

    // 前端 登出
    FedLogOut(context) {
      return new Promise(resolve => {
        resolve()
      })
    },
    getDisplayOriginalPrice({ commit }, displayOriginalPrice) {
      commit('SET_DISPLAYORIGINALPRICE', displayOriginalPrice)
    }
  }
}

export default user
